package com.scoresystem.dao.impl;

import java.sql.Connection;

import java.sql.ResultSet;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.scoresystem.common.CommonValue;
import com.scoresystem.dao.IUserDao;
import com.scoresystem.exception.UserRepeatException;
import com.scoresystem.model.User;
import com.scoresystem.utils.ResultMapUtil;

public class UserDaoImpl extends BaseDaoImpl implements IUserDao {

	public UserDaoImpl(Connection conn) {
		super(conn);
		this.conn=conn;
	}
	/**
	 * 对查找的重复操作进行封装
	 * @return
	 */
	private User find(String sql){
		try{
			ResultSet rs=this.templateQuery(sql);
			User user=new User();
			if(rs.next()){
				Map<String,String> map=ResultMapUtil.getResultMap(rs);
				try{
					BeanUtils.populate(user, map);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			else {
				return null;
			}
			//如果还有记录，说明名字有重复，向上抛出异常
			if(rs.next())
				throw new UserRepeatException("you have a repeated user");
			else 
				return user;
				
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	/**
	 * 如果返回多个，向上则抛出异常
	 */
	public User findByName(String name) throws UserRepeatException{
		String sql="select * from "+CommonValue.TAB_USER+" where name="+"'"+name+"'";
		return find(sql);
	}

	@Override
	public User findByUsername(String username)throws UserRepeatException {
		String sql="select * from "+CommonValue.TAB_USER+" where username="+"'"+username+"'";
		return find(sql);
	}

	@Override
	public boolean add(User user) {
		String sql="insert into "+CommonValue.TAB_USER+" (username,password"
				+ ",post,name)"+"values"+"("+
				"'"+user.getUsername()+"'"+
				","+"'"+user.getPassword()+"'"+","
				+"'"+user.getPost()+"'"+","
				+"'"+user.getName()+"'"+")";
		try{
			this.templateUpdate(sql);
			return true;
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean deleteUsers(String[] username) {
		
		try{
			for(String username1:username){
				String sql="delete from "+CommonValue.TAB_USER+" where username="
						+"'"+username1+"'";
				this.templateUpdate(sql);
			}
			return true;
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	@Override
	public User findByNamePsd(String username, String password) {
		String sql="select * from "+CommonValue.TAB_USER+" where username="+"'"+username+"'"
				+" and password="+"'"+password+"'";
		return find(sql);
	}
	@Override
	public boolean modify(User user) {
		String sql="update user set username="+"'"+user.getUsername()+"'"+","
				+ " password="+"'"+user.getPassword()+"'"+","
				+" post="+"'"+user.getPost()+"'"+","
				+" name="+"'"+user.getName()+"'"
				+" where username="+"'"+user.getUsername()+"'";
		try{
			this.templateUpdate(sql);
			return true;
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}

}
